import { ref, Ref } from 'vue'
/**
 *触底加载hooks
 */
type PaginationParams = {
  current: number
  size: number
  [key: string]: any
}

type PaginationOptions<T> = {
  apiMethod: (params: any) => Promise<IResData<PageResult<T>>>
  initialParams?: Record<string, any>
}

export function usePagination<T>(options: PaginationOptions<T>) {
  const loading = ref(false)
  const finished = ref(false)
  const error = ref(false)
  const list: Ref<T[]> = ref([])
  const params = ref<PaginationParams>({
    current: 1,
    size: 10,
    ...options.initialParams,
  })

  const loadData = async () => {
    if (loading.value || finished.value) return

    loading.value = true
    error.value = false

    try {
      const res = await options.apiMethod(params.value)
      if (res.code === 200 && res.data) {
        list.value =
          params.value.current === 1 ? res.data.records : [...list.value, ...res.data.records]

        finished.value = res.data.records.length < params.value.size
        params.value.current++
      }
    } catch (err) {
      error.value = true
      console.error('加载失败:', err)
    } finally {
      loading.value = false
    }
  }

  const reset = () => {
    params.value.current = 1
    list.value = []
    finished.value = false
    error.value = false
  }

  return {
    loading,
    finished,
    error,
    list,
    params,
    loadData,
    reset,
  }
}
